package com.markul.android.ui.detail

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.*
import com.markul.android.MarkulApplication
import com.markul.android.R
import com.markul.android.logic.model.Repository
import com.markul.android.ui.UiTool
import com.markul.android.ui.main.MainActivity
import com.markul.android.ui.personal.BufferActivity
import kotlinx.android.synthetic.main.activity_detailed.*
import kotlinx.android.synthetic.main.activity_detailed.addressText
import kotlinx.android.synthetic.main.activity_detailed.backBtn
import kotlinx.android.synthetic.main.activity_detailed.chooseIconRecycler
import kotlinx.android.synthetic.main.activity_detailed.dateText
import kotlinx.android.synthetic.main.activity_detailed.editTextTextMultiLine
import kotlinx.android.synthetic.main.activity_detailed.keyText
import kotlinx.android.synthetic.main.activity_detailed.picRecycler
import kotlinx.android.synthetic.main.activity_mark.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class DetailedActivity : AppCompatActivity(), OnGetGeoCoderResultListener {

    private lateinit var detailAdapter: DetailedAdapter
    private lateinit var detailedIconAdapter: DetailedIconAdapter
    var handler = Handler()

    private var mLocClient: LocationClient? = null
    val myListener = MyLocationListener()
    var mMapView: MapView? = null
    var mBaiduMap: BaiduMap? = null
    var mSearch: GeoCoder? = null

    // 用于设置个性化地图的样式文件
    private val CUSTOM_FILE_NAME_CX = "custom_map_config_CX.sty"

    // 是否首次定位
    var isFirstLoc = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detailed)
        UiTool.hideStatusNavigationBar(this, true)

        //接受上一级页面的信息
        val extraData = intent.getStringExtra("number")
        val extraPosition = intent.getIntExtra("position", 0)
        val extraId = intent.getIntExtra("id", 0)
        val viewModel: DetailedViewModel by viewModels()
        detailAdapter = DetailedAdapter(viewModel.picList)
        detailedIconAdapter = DetailedIconAdapter(viewModel.IconList)

        backBtn.setOnClickListener {
            finish()
            val intent = Intent(this, BufferActivity::class.java)
            startActivity(intent)
        }
        delBtn.setOnClickListener {
            viewModel.deleteAlbumAndPhotos(extraId)
            MarkulApplication.delId=extraId
            finish()
        }

        //地图初始化
        mMapView = findViewById<View>(R.id.bmapView) as MapView
        mBaiduMap = mMapView!!.map
        mMapView!!.showZoomControls(false)
        mMapView!!.showScaleControl(false)
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance()
        mSearch!!.setOnGetGeoCodeResultListener(this)
        //改变地图样式
        changeMapStyle()
        //改变定位图标
        changeLocationIcon()
        if (extraData == "only") {
            picRecycler.layoutManager =
                StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
            picRecycler.adapter = detailAdapter
            chooseIconRecycler.layoutManager =
                StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
            chooseIconRecycler.adapter = detailedIconAdapter
            Repository.allPhotos.observe(this, {
                viewModel.picList.add(it[extraPosition].photoList[0].photoUrl)
                viewModel.latLng = LatLng(it[extraPosition].album.lat, it[extraPosition].album.lng)
                viewModel.IconList.add(it[extraPosition].album.albumIcon1)
                viewModel.IconList.add(it[extraPosition].album.albumIcon2)
                viewModel.IconList.add(it[extraPosition].album.albumIcon3)
                viewModel.dateText = it[extraPosition].album.albumTime
                viewModel.markText = it[extraPosition].album.albumText
                dateText.text = viewModel.dateText
                editTextTextMultiLine.text = viewModel.markText
                setCenter(viewModel.latLng)
                addMarker(viewModel.latLng, viewModel.IconList[0])
                searchAddressByLocation(viewModel.latLng)
                detailAdapter.notifyDataSetChanged()
                detailedIconAdapter.notifyDataSetChanged()
            })
        } else {
            picRecycler.layoutManager =
                StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
            picRecycler.adapter = detailAdapter
            chooseIconRecycler.layoutManager =
                StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
            chooseIconRecycler.adapter = detailedIconAdapter
            Repository.allPhotos.observe(this, {

                var photos = it[extraPosition].photoList
                for (i in photos) {
                    viewModel.picList.add(i.photoUrl)
                }
                viewModel.latLng =
                    LatLng(it[extraPosition].album.lat, it[extraPosition].album.lng)
                viewModel.IconList.add(it[extraPosition].album.albumIcon1)
                viewModel.IconList.add(it[extraPosition].album.albumIcon2)
                viewModel.IconList.add(it[extraPosition].album.albumIcon3)
                viewModel.dateText = it[extraPosition].album.albumTime
                viewModel.markText = it[extraPosition].album.albumText
                dateText.text = viewModel.dateText
                editTextTextMultiLine.text = viewModel.markText
                setCenter(viewModel.latLng)
                addMarker(viewModel.latLng, viewModel.IconList[0])
                searchAddressByLocation(viewModel.latLng)
                detailAdapter.notifyDataSetChanged()
                detailedIconAdapter.notifyDataSetChanged()

            })
        }
    }


    //增加打卡点
    private fun addMarker(point: LatLng, picId: Int?) {
        //构建Marker图标
        var bitmap: BitmapDescriptor
        if (picId == null) {
            bitmap = BitmapDescriptorFactory
                .fromResource(MarkulApplication.headImage)
        } else {
            bitmap = BitmapDescriptorFactory
                .fromResource(picId)
        }
        //构建MarkerOption，用于在地图上添加Marker
        val option: OverlayOptions = MarkerOptions()
            .position(point)
            .icon(bitmap)
            .perspective(true)
            .animateType(MarkerOptions.MarkerAnimateType.grow)
        //在地图上添加Marker，并显示
        mBaiduMap!!.addOverlay(option)
    }

    //设置地图中心
    private fun setCenter(point: LatLng) {
        //设定中心点坐标
        //定义地图状态
        val mMapStatus: MapStatus = MapStatus.Builder()
            .target(point)
            .zoom(15.0f)
            .build()
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        val mMapStatusUpdate = MapStatusUpdateFactory
            .newMapStatus(mMapStatus)
        //改变地图状态
        mBaiduMap!!.setMapStatus(mMapStatusUpdate)
    }

    private fun changeMapStyle() {
        // 构建地图状态
        val builder = MapStatus.Builder()
        // 更新地图
        mMapView!!.map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
        // 获取.sty文件路径
        val customStyleFilePath: String? =
            getCustomStyleFilePath(this, CUSTOM_FILE_NAME_CX)
        // 设置个性化地图样式文件的路径和加载方式
        mMapView!!.setMapCustomStylePath(customStyleFilePath)
        // 动态设置个性化地图样式是否生效
        mMapView!!.setMapCustomStyleEnable(true)
    }

    private fun changeLocationIcon() {
        val mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL
        val accuracyCircleFillColor = -0x55000078
        val accuracyCircleStrokeColor = 0x55ff0100
        //修改为自定义图层
        var mcurrentMarker = BitmapDescriptorFactory.fromResource(MarkulApplication.headImage)
        mBaiduMap!!.setMyLocationConfiguration(
            MyLocationConfiguration(
                mCurrentMode, true, mcurrentMarker,
                accuracyCircleFillColor, accuracyCircleStrokeColor
            )
        )
    }

    private fun initLocation() {
        // 开启定位图层
        mBaiduMap!!.isMyLocationEnabled = true
        // 定位初始化
        mLocClient = LocationClient(this)
        mLocClient!!.registerLocationListener(myListener)
        val option = LocationClientOption()
        // 打开gps
        option.isOpenGps = true
        // 设置坐标类型
        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy
        option.setCoorType("bd09ll")
        option.setScanSpan(1000)
        mLocClient!!.locOption = option
        mLocClient!!.start()
    }

    override fun onResume() {
        super.onResume()

        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView!!.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView!!.onPause()
    }

    override fun onDestroy() {
        // 退出时销毁定位
//        mLocClient!!.stop()
        mBaiduMap!!.isMyLocationEnabled = false
        mMapView!!.onDestroy()
        mMapView = null
        MarkulApplication.isStartNewAcitity = false
        super.onDestroy()
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
    }

    //获取个性化地图文件地址
    private fun getCustomStyleFilePath(context: Context, customStyleFileName: String): String? {
        var outputStream: FileOutputStream? = null
        var inputStream: InputStream? = null
        var parentPath: String? = null
        try {
            inputStream = context.assets.open("customConfigdir/$customStyleFileName")
            val buffer = ByteArray(inputStream.available())
            inputStream.read(buffer)
            parentPath = context.filesDir.absolutePath
            val customStyleFile = File("$parentPath/$customStyleFileName")
            if (customStyleFile.exists()) {
                customStyleFile.delete()
            }
            customStyleFile.createNewFile()
            outputStream = FileOutputStream(customStyleFile)
            outputStream.write(buffer)
        } catch (e: IOException) {
            Log.e("CustomMapDemo", "Copy custom style file failed", e)
        } finally {
            try {
                inputStream?.close()
                outputStream?.close()
            } catch (e: IOException) {
                Log.e("CustomMapDemo", "Close stream failed", e)
                return null
            }
        }
        return "$parentPath/$customStyleFileName"
    }

    //定位监听器
    inner class MyLocationListener : BDLocationListener {
        override fun onReceiveLocation(location: BDLocation) {
            // MapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return
            }
            val locData = MyLocationData.Builder()
                .accuracy(location.radius) // 设置定位数据的精度信息，单位：米
                .direction(location.direction) // 此处设置开发者获取到的方向信息，顺时针0-360
                .latitude(23.0540551376)
                .longitude(113.4130708748)
                .build()
            // 设置定位数据, 只有先允许定位图层后设置数据才会生效
            mBaiduMap!!.setMyLocationData(locData)
            if (isFirstLoc) {
                isFirstLoc = false
                val latLng = LatLng(23.0540551376, 113.4130708748)
                val builder = MapStatus.Builder()
                builder.target(latLng).zoom(15.0f)
                mBaiduMap!!.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
            }
        }
    }

    fun searchAddressByLocation(point: LatLng) {
        val radius: Int = 100
        var version = 1
        // 反Geo搜索
        val reverseGeoCodeOption = ReverseGeoCodeOption()
            .location(point) // 设置反地理编码位置坐标
            .newVersion(version) // 设置是否返回新数据 默认值0不返回，1返回
            .radius(radius) //  POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
            .pageNum(0)
        // 发起反地理编码请求，该方法必须在监听之后执行，否则会在某些场景出现拿不到回调结果的情况
        mSearch!!.reverseGeoCode(reverseGeoCodeOption)
    }

    /**
     * 逆地理编码查询回调结果
     *
     * @param result 逆地理编码查询结果
     */
    override fun onGetReverseGeoCodeResult(result: ReverseGeoCodeResult?) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            return
        }
        val bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_add)
        // 添加poi
        mBaiduMap!!.addOverlay(MarkerOptions().position(result.location).icon(bitmapDescriptor))
        // 获取周边poi结果
        if (result.poiList != null) {
            val poiList = result.poiList
            keyText.text = poiList[0].getName()
            addressText.text = poiList[0].getAddress()
        } else if (result.poiList == null && result.address != "") {
            keyText.text = result.addressDetail.city
            addressText.text =
                "${result.addressDetail.countryName}-${result.addressDetail.province}"
        }
    }


    override fun onGetGeoCodeResult(result: GeoCodeResult?) {}
}